package com.xiaoyi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoyi.entity.SysMenu;
import com.xiaoyi.entity.SysRole;
import com.xiaoyi.entity.SysUser;
import com.xiaoyi.mapper.SysMenuMapper;
import com.xiaoyi.mapper.SysRoleMapper;
import com.xiaoyi.service.SysRoleService;
import com.xiaoyi.service.SysUserRoleService;
import com.xiaoyi.service.SysUserService;
import com.xiaoyi.mapper.SysUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author 小易
* @description 针对表【sys_user】的数据库操作Service实现
* @createDate 2022-12-04 12:00:39
*/

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService{

    @Resource
    private SysRoleMapper roleMapper;

    @Resource
    private SysMenuMapper menuMapper;

    @Override
    public SysUser getByUsername(String username) {
        return getOne(new QueryWrapper<SysUser>().eq("username", username));
    }

    @Override
    public String getUserAuthorityInfo(long userId) {
        StringBuilder authority = new StringBuilder();
        // 获取该用户的所有角色，添加到权限列表中
        List<SysRole> roleList = roleMapper.selectList(new QueryWrapper<SysRole>().inSql("id", "SELECT role_id FROM sys_user_role WHERE user_id = " + userId));
        String roleStr = roleList.stream().map(role -> "ROLE_" + role.getCode()).collect(Collectors.joining(","));
        authority.append(roleStr);
        // 通过用户的角色信息获取所有权限信息，需要去重
        Set<String> menuSet = new HashSet<>();
        for (SysRole sysRole : roleList) {
            List<SysMenu> menuList = menuMapper.selectList(new QueryWrapper<SysMenu>().inSql("id", "SELECT menu_id FROM sys_role_menu WHERE role_id = " + sysRole.getId()));
            menuList.forEach(m->{
                // 可能有的菜单没有权限编码。所有可能会出现编码为空，在添加的时候需要判断
                if (StringUtils.hasText(m.getPerms())){
                    menuSet.add(m.getPerms());
                }
            });
        }
        if (menuSet.size() > 0){
            String menuStr = String.join(",", menuSet);
            authority.append(",").append(menuStr);
        }
        System.out.println("authority==============" + authority);
        return authority.toString();
    }
}




